import Vue from 'vue'
import Vuex from 'vuex'
import portal from "~/net/portal"

Vue.use(Vuex)

const store = () => new Vuex.Store({
    state: {
        user: null,
        patentCount: 0,
        identities: []
    },
    mutations: {
        SET_USER(state, user) {
            state.user = user
        },
        SET_PatentCount(state, patentCount) {
            state.patentCount = patentCount
        },
        SET_IDENTITY(state, identities) {
            state.identities = identities
        }
    },
    actions: {
        LoginIn({ commit }, userinfo) {
            return new Promise((reslove, reject) => {
                portal.login({
                    body: userinfo,
                    client: true
                }).then((res) => {
                    commit('SET_USER', res.data)
                }).then(() => {
                    portal.identities().then(res => {
                        commit('SET_IDENTITY', res.data)
                    })
                    reslove();
                }).catch(error => {
                    reject(error)
                })
            })
        },
        LogOut({ commit }) {
            portal.signout().then(res => {
                commit('SET_USER', null);
                commit('SET_IDENTITY', [])
            })
        }
    }
})

export default store